<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js的Map的测试</title>
    <script src="../../js/jquery-3.4.1.js"></script>
</head>
<body>

</body>
<script>

    let map = new Map();
    map.set(1, "s1");
    map.set(2, "s2");
    map.set(3, "s3");
    map.set(4, "s4");
    map.set(6, {
        id: 1,
        name: 's1',
        age: 12
    });

    //map可以接受2个参数的数组为参数进行构造
    let map1 = new Map([
        ['name', '张三'],
        ['title', 'Author']
    ]);

    $(() => {
        mapMethodHas();
        mapMethodGetOrSet();
        mapForeach();
        mapToJson();
        test222();
    });

    function mapMethodHas() {
        console.log(map.has(5) ? 'map包含这个5这个key' : 'map不包含这个5这个key');
        console.log(map.has(3) ? 'map包含这个3这个key' : 'map不包含这个5这个key');
    }

    function mapMethodGetOrSet() {
        let obj = map.get(6);
        console.log(obj.id, obj.name, obj.age);

        map.set(9, '999皮炎平');
        console.log(map.get(9));
    }

    function mapForeach() {
        console.log("---foreach---");
        map.forEach((value, key) => {
            console.log(value, key);
        });
    }

    function mapToJson() {
        console.log("---Map2JSON---");
        console.log(JSON.stringify(map2obj(map)));
        console.log("---JSON2Map---");
        let obj = {
            id: 1,
            address: ['s1', 's2', 's3'],
            family: {
                id: 2,
                name: 's3'
            }
        };
        let map3 = obj2map(obj);
        for(let[k, v] of map3) {
            console.log(k, v);
        }
    }

    function map2obj(map) {
        let obj= Object.create(null);
        for (let[k,v] of map) {
            obj[k] = v;
        }
        return obj;
    }

    function obj2map(obj) {
        let tempMap = new Map();
        for (let k of Object.keys(obj)) {
            tempMap.set(k, obj[k]);
        }
        return tempMap;
    }

    function test222() {
        console.log("---test222---");
        let a = new Map();
        a.set("1", "s1,s2,s3,s4".split(","));
        console.log(JSON.parse(JSON.stringify(a.get("1"))));
    }

</script>
</html>